<template>
  <el-select
    v-model="dataValue"
    v-bind="$attrs"
    @change="handleChange"
  >
    <el-option
      v-for="option in options"
      :key="option.value"
      :label="option.label"
      :value="option[props.valueProp]"
    />
  </el-select>
</template>

<script setup lang="ts" name="FormOptionSelect">
import { ref, watch } from "vue";
import { useFormOption } from "@/views/formgen/components/FormItem/hooks/useFormOptionHook";
import { removeHtmlTag } from "@/views/formgen/utils";

const props = defineProps({
  value: {
    type: String,
    default: ""
  },
  item: {
    type: Object,
    default: () => {}
  },
  valueProp: {
    type: String,
    default: "label"
  }
});
const dataValue = ref(props.value);
const options = ref<any[]>([]);

const formOptions = useFormOption();

const getOptions = async (item: any) => {
  if (!item) {
    return;
  }
  const config = item.config;
  if (config!.optionsType == 0) {
    options.value = config!.options.map((item: any) => {
      return {
        label: removeHtmlTag(item.label),
        value: item.value
      };
    });
  } else {
    options.value = await formOptions.getOptions(config);
  }
};

watch(
  () => props.item,
  val => {
    if (val && val.field) {
      getOptions(props.item?.field?.scheme);
    }
  },
  {
    immediate: true,
    deep: true
  }
);

const emit = defineEmits(["input"]);
const handleChange = () => {
  emit("input", dataValue.value);
};
</script>

<style scoped lang="scss"></style>
